package com.zlx.xbhy.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.kaptcha.Kaptcha;
import com.zlx.xbhy.entity.Result;
import com.zlx.xbhy.entity.User;
import com.zlx.xbhy.entity.UserFocus;
import com.zlx.xbhy.service.UserFocusService;
import com.zlx.xbhy.service.UserService;
import com.zlx.xbhy.webSocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.*;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @Author 周罗校
 * @Description
 * @ClassName UserController
 * @date 2020.11.17 19:49:53
 * 该版权归周罗校所有，最终解释权以官方为准
 */
@RestController()
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private Kaptcha kaptcha;
    @Autowired
    private UserFocusService userFocusService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * @Author Edward
     * @Description 登录的页面
     * @Date 22:31 2020/11/17
     * @Param [username, password, code]
     * @return com.zlx.xbhy.entity.Result
     **/
    @GetMapping("/login/{remberMe}")
    public Result login(@PathVariable Boolean remberMe, String username, String password, String code, HttpSession session, HttpServletResponse response){
        String message = null;
        if (StringUtils.isEmpty(code)){
            message="验证码不能为空！";
        }else {
            if (kaptcha.validate(code)) {//验证码正确
                User user = new User();
                user.setPassword(password);
                user.setUsername(username);
                user = userService.selectOne(user);
                if (!StringUtils.isEmpty(user)) {//用户名正确
                    //置空密码
                    user.setPassword(null);
                    session.setAttribute("loginUser",user);
                    if (remberMe){
                        //免密码登陆
                        String encodeCookie = URLEncoder.encode(JSONObject.toJSONString(user));
                        Cookie cookie = new Cookie("loginUser", encodeCookie);
                        cookie.setPath("/");
                        //最大7天
                        cookie.setMaxAge(60*60*24*7);
                        response.addCookie(cookie);
                    }
                    return new Result(user);
                }
            } else {
                //验证码错误
                message = "验证码错误";
            }
        }
        return new Result(false,message,null);
    }
    @GetMapping("/selectPage/{start}/{pageSize}")
    public Result selectPage(String userName,@PathVariable("start") Integer start,@PathVariable("pageSize") Integer pageSize){
        return new Result(userService.selectPage(userName,start,pageSize));
    }
    @GetMapping("/getFocus/{userId}")
    public Result getFocus(@PathVariable Long userId){
        UserFocus userFocus = new UserFocus();
        userFocus.setUserId(userId);
        return new Result(userFocusService.select(userFocus));
    }
    //关注
    @PostMapping("/focus")
    public Result focusUser (@RequestBody UserFocus focus,HttpSession session){
        userFocusService.focusUser(focus);
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser!=null){
            WebSocketServer.sendMsg(focus.getUserFocusId(),loginUser.getRealName()+"关注了你");
        }
        return new Result(true,"关注成功！",null);
    }
    //取消关注
    @PutMapping("/cancekFocus")
    public Result cancekFocus (@RequestBody UserFocus focus){
        userFocusService.cancelFocusUser(focus);
        return new Result(true,"取消关注成功！",null);
    }
    //获取已关注的用户
    @GetMapping("/selectFocusUsers/{start}/{pageSize}")
    public Result selectFocusUsers(Long userId,@PathVariable("start") Integer start,@PathVariable("pageSize") Integer pageSize){
        return new Result(userService.selectFocusUsers(userId,start,pageSize));
    }
    @GetMapping("/selectMulFavoriteUsers/{uId}/{aId}")
    public Result selectMulFavoriteUsers(@PathVariable("uId") Long uId,@PathVariable("aId") Long aId){
        return new Result(userService.selectMulFavoriteUser(uId,aId));
    }
    @GetMapping("selectAll")
    public Result selectAll(){
        return new Result(userService.selectAll());
    }
    @GetMapping("getFansCount/{uId}")
    public Result getFansCount(@PathVariable Long uId){
        UserFocus userFocus = new UserFocus();
        userFocus.setUserFocusId(uId);
        return new Result(userFocusService.selectCount(userFocus));
    }
    //用户注册
    @PostMapping("register")
    public Result register(@RequestBody User user){
//        User checkUser = new User();
        User checkUser = new User();
        String username = user.getUsername();
        checkUser.setUsername(username);
        checkUser=userService.selectOne(checkUser);
        if (checkUser==null) {
            user.setIsSecret("0");
            user.setLoginTime(new Date());
            user.setRegisterTime(new Date());
            return new Result(true, "用户注册成功!", userService.insert(user));
        }
        else
            return new Result(false,"用户已存在！！！",null);
    }
    //忘记密码
    @PutMapping("forget/{code}")
    public Result forget(@RequestBody User user,@PathVariable("code") String code){
        //获取验证码
        String check = redisTemplate.opsForValue().get("com.zlx.xbhy.service.impl.IMailServiceImpl:" + user.getEmail());
        User exitsUser = new User();
        exitsUser.setEmail(user.getEmail());
        //错误提示信息
        String msg=null;
        //用户邮箱是否存在
        exitsUser=userService.selectOne(exitsUser);
        if (exitsUser!=null) {   //用户邮箱存在
            if (code.equals(check)) {//验证码正确
                user.setId(exitsUser.getId());
                user.setEmail(null);
                return new Result(true,"修改密码成功！",userService.updateByPrimaryKeySelective(user));
            }else {
                msg="用户验证码错误，请审核后再填写！！！";
            }
        }else {
            msg="邮箱不存在，请确认后再填写！！！";
        }
        return new Result(false,msg,null);
    }

    //获取关注的数量、
    @GetMapping("selectFavorites/{uid}")
    public Result selectFavorites(@PathVariable Long uid){
        UserFocus userFocus = new UserFocus();
        userFocus.setUserId(uid);
        return new Result(userFocusService.selectCount(userFocus));
    }

    //修改基本的个人信息
    @PutMapping("update")
    public Result update(@RequestBody User user){
        user.setPic(null);
        userService.updateByPrimaryKeySelective(user);
        return new Result(true,"修改完成！",userService.selectByPrimaryKey(user.getId()));
    }

    //获取loginUser
    @GetMapping("getLoginUser")
    public Result getLoginUser(HttpServletRequest request){
        return new Result(request.getSession().getAttribute("loginUser"));
    }
}
